package com.ttfeed.server.common.config;

import com.ttfeed.server.common.enums.SpringConvertibleEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class EnumConverter implements ConverterFactory<String, SpringConvertibleEnum> {
    @Override
    public <T extends SpringConvertibleEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new IntegerToEnum<>(targetType);
    }

    private static class IntegerToEnum<T extends SpringConvertibleEnum> implements Converter<String, T> {

        private final T[] values;

        public IntegerToEnum(Class<T> targetType) {
            values = targetType.getEnumConstants();
        }

        @Override
        public T convert(String source) {
            for (T t : values) {
                if (t.getCode() == Integer.parseInt(source)) {
                    return t;
                }
            }
            return null;
        }
    }
}
